package com.chinait.web.wechat;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.chinait.utils.RequestUtils;
import com.chinait.vo.ReceiveXmlEntity;
import com.chinait.vo.ReceiveXmlProcess;
import com.chinait.vo.WechatProcess;
/**
 * 处理微信的对话服务
 * @author cyc
 */
@Controller
@RequestMapping("dialogueWechat")
public class DialogueWechatController {
	private static final Logger log = Logger.getLogger(DialogueWechatController.class);
	@RequestMapping("fromWechat")
	public String fromWechat(HttpServletRequest request,HttpServletResponse response){
		log.info("fromWeiXin==============:start");
		PrintWriter os = null;
        try {
        	request.setCharacterEncoding("UTF-8");  
            response.setCharacterEncoding("UTF-8");
	        String xml = RequestUtils.streamToXml(request);
	        log.info("xml:"+xml);
	        String result = "";  
	        /** 判断是否是微信接入激活验证，只有首次接入验证时才会收到echostr参数，此时需要把它直接返回 */  
	        String echostr = request.getParameter("echostr");
	        log.info("判断是否是微信接入激活验证echostr:"+echostr);
	        if (echostr != null && echostr.length() > 1) {  
	            result = echostr;  
	        } else {
	        	log.info("微信传入的数据:"+xml);
	        	ReceiveXmlEntity xmlEntity = new ReceiveXmlProcess().getMsgEntity(xml); 
	        	log.info("xml:"+xmlEntity);
	            /** 正常的微信处理流程 */
	            result = new WechatProcess().rePly(xmlEntity);  
	        }
		    // 响应消息
	        os = response.getWriter();
	        os.print(result);
	        log.info("fromWeiXin==============:end");
        } catch (Exception e) {  
        	log.error("微信传入的数据:",e);
        }finally {
        	os.close(); 
		}
		return "";
	}
}
